'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as walk from 'walk';
import * as path from 'path';



// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('[openutils]:Congratulations, your extension "openutils" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    
    let disposable = vscode.commands.registerCommand('open-utils.open-python-folder', (fileUri: vscode.Uri) => {
        /*
        1. 判断是不是文件夹右键
        2. 获取所有的python文件
        3. 用vscode打开这些文件
        4. 调用 python的runlint命令
        
        
        
        */
        // The code you place here will be executed every time your command is executed
        // textEditor.
        // Display a message box to the user
        let absolute_path = fileUri.fsPath;
        if(fs.existsSync(absolute_path) ) {
            let path_stat = fs.lstatSync(absolute_path);
            if(!path_stat.isDirectory()){
                throw new Error(`path {absolute_path} is not a directory`);
            }
        }
        vscode.window.showInformationMessage("absolute_path:" + absolute_path);
        let walker = walk.walk(absolute_path, {});
        let absolute_python_files = [];
        let { document } = vscode.window.activeTextEditor;
        walker.on("file", function (root, fileStats, next) {
            let name: string = fileStats.name;
            if(name.endsWith(".py")) {
                let absolute_path = path.join(root, fileStats.name);
                absolute_python_files.push(absolute_path);
            }
            next();
            

            // fs.readFile(fileStats.name, function () {
            //   // doStuff
            //   next();
            // });
          });
        walker.on("end", function() {

            for(let i=0;i<absolute_python_files.length;i ++) {
                let newUri = document.uri.with({ path: absolute_python_files[i] });
                vscode.window.showTextDocument(newUri, { preview: false });
            }
        });
        
        
        // vscode.window.showInformationMessage('Hello World!');
    });

    context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
export function deactivate() {
}